// pages/smartlife/post_auto_insurance/insurance_add/insurance_add.js
var util = require('../../../../utils/util.js');
var common = require("../../../../utils/common.js");
//获取应用实例
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    plate: "苏",
    phone:"",
    companyArray: ['人保', '太平洋', '平安', '天安', '阳光', '人寿', '太平', '紫金', '大地'],
    thirdArray: ['5万', '10万', '20万', '30万', '50万', '100万', '200万'],
    companyIndex: 0,
    thirdIndex: 4,
    chesun:true,
    huahen:false,
    daoqiang:false,
    ziran:false,
    boli:false,
    zuowei:false,
    bujimianpei:true,
    guohu:false,
    fdjtbssx:false,
    remark:'',
    address:'',
    latitude:'',
    longitude:'',
    formId:'',
    btnFinishLoading: false,
    btnAgainLoading: false,
    btnDeleteLoading: false,
    finishText: "申请报价",
    deleteText: "删除",
    id: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if (app.globalData.wangcaiToken) {
      if (options.id != null) {//添加
        that.setData({
          finishText: "重新报价",
          id: options.id
        })
        that.detailData()
      }
    } else {
      // console.log("间接获取")
      //调用应用实例的方法获取全局数据
      app.getToken(function (wangcaiToken) {
        //更新数据
        if (options.id != null) {//添加
          that.setData({
            finishText: "重新报价",
            id: options.id
          })
          that.detailData()
        }
      })
    }
  },
  onShareAppMessage: function () {
    return {
      title: '买车险到邮政，方便快捷',
      path: '/pages/smartlife/post_auto_insurance/insurance_add/insurance_add'
    }
  },
  companyPickerChange: function (e) {
    this.setData({
      companyIndex: e.detail.value
    })
  },
  thirdPickerChange: function (e) {
    this.setData({
      thirdIndex: e.detail.value
    })
  },
  plateInput: function (e) {
    this.setData({
      plate: e.detail.value
    })
  },
  phoneInput: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },
  remarkInput: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  addressInput: function (e) {
    this.setData({
      address: e.detail.value
    })
  },
  location: function (e) {
    var that = this
    wx.chooseAddress({
      success: function (res) {
        that.setData({
          address: res.provinceName + res.cityName + res.countyName + res.detailInfo
        })
        // console.log(res.userName)
        // console.log(res.postalCode)
        // console.log(res.provinceName)
        // console.log(res.cityName)
        // console.log(res.countyName)
        // console.log(res.detailInfo)
        // console.log(res.nationalCode)
        // console.log(res.telNumber)
      }
    })
    // wx.chooseLocation({
    //   success: function(res) {
    //     that.setData({
    //       address:res.address,
    //       latitude:res.latitude,
    //       longitude:res.longitude
    //     })
    //   },
    // })
  },
  changeCheSun: function (e) {
    var that = this
    that.setData({
      chesun: !that.data.chesun
    })
  },
  changeHuaHen: function (e) {
    var that = this
    that.setData({
      huahen: !that.data.huahen
    })
  },
  changeDaoQiang: function (e) {
    var that = this
    that.setData({
      daoqiang: !that.data.daoqiang
    })
  },
  changeZiRan: function (e) {
    var that = this
    that.setData({
      ziran: !that.data.ziran
    })
  },
  changeBoLi: function (e) {
    var that = this
    that.setData({
      boli: !that.data.boli
    })
  },
  changeZuoWei: function (e) {
    var that = this
    that.setData({
      zuowei: !that.data.zuowei
    })
  },
  changeBJMP: function (e) {
    var that = this
    that.setData({
      bujimianpei: !that.data.bujimianpei
    })
  },
  changeGuoHu: function (e) {
    var that = this
    that.setData({
      guohu: !that.data.guohu
    })
  },
  changeFDJTBSSX: function (e) {
    var that = this
    that.setData({
      fdjtbssx: !that.data.fdjtbssx
    })
  },
  btnComplete: function (e) {
    var that = this
    // 设置按钮加载状态
    this.setData({
      btnFinishLoading: true,
      finishText: "申请中…",
      formId:e.detail.formId
    })
    that.submitData(function (res) {
      //更新按钮状态
      if (that.data.id == null) {//添加
        that.setData({
          btnFinishLoading: false,
          finishText: "申请报价"
        })
      }else{
        that.setData({
          btnFinishLoading: false,
          finishText: "重新报价"
        })
      }
      if (res.status == -1) {
      } else {
        wx.showModal({
          title: '报价成功',
          content: '您将在1~2个工作日接收到报价短信和推送消息，请注意查收',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              //刷新上一页数据
              var pages = getCurrentPages();
              if (pages.length > 1) {
                //上一个页面实例对象
                var prePage = pages[pages.length - 2];
                prePage.getData()
              }
              wx.navigateBack({
                delta: 1
              })
            }
          }
        })
      }
    })
  },
  btnDelete: function (e) {
    var that = this
    that.deleteRecord(function (res) {
      if (res.status == -1) {
      } else {
        //刷新上一页数据
        var pages = getCurrentPages();
        if (pages.length > 1) {
          //上一个页面实例对象
          var prePage = pages[pages.length - 2];
          prePage.getData()
        }
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },
  submitData: function (cb) {
    var that = this;
    var plate = that.data.plate.toUpperCase()
    var phone = that.data.phone
    var company = that.data.companyIndex
    var third = that.data.thirdArray[that.data.thirdIndex]
    third = third.substring(0, third.length-1)
    var insurancetype = (that.data.chesun ? '0,' : '') + (that.data.huahen ? '1,' : '') + (that.data.daoqiang ? '2,' : '') + (that.data.ziran ? '3,' : '') + (that.data.boli ? '4,' : '') + (that.data.zuowei ? '5,' : '') + (that.data.bujimianpei ? '6,' : '') + (that.data.guohu ? '7,' : '') + (that.data.fdjtbssx ? '8,' : '')
    if (insurancetype.length>1){
      insurancetype = insurancetype.substring(0, insurancetype.length-1)
    }
    var remark = that.data.remark
    var address = that.data.address
    var latitude = that.data.latitude
    var longitude = that.data.longitude

    var regCN = new RegExp('^[0-9a-zA-Z]*$', 'g');
    var returnRes = null
    
    if (regCN.exec(plate.substring(1, plate.length)) == null) {
      wx.showModal({
        title: '错误提示',
        content: '车牌只能为数字和字母，请重新输入',
        showCancel: false
      })
      returnRes = {
        "status": -1,
        "msg": "车牌只能为数字和字母，请重新输入"
      }
      typeof cb == "function" && cb(returnRes)
      return
    }

    if (plate.length != 7) {
      wx.showModal({
        title: '错误提示',
        content: '车牌位数不正确，请重新输入',
        showCancel: false
      })
      returnRes = {
        "status": -1,
        "msg": "车牌位数不正确，请重新输入"
      }
      typeof cb == "function" && cb(returnRes)
      return
    }

    if (phone.length != 11) {
      wx.showModal({
        title: '错误提示',
        content: '手机号不正确',
        showCancel: false
      })
      returnRes = {
        "status": -1,
        "msg": "手机号不正确"
      }
      typeof cb == "function" && cb(returnRes)
      return
    }
    // if(that.data.id == null){
      //新增请求
      wx.request({
        url: common.postUrl() + 'applyAutoInsurance',
        data: that.data.id == null ? {
          token: app.globalData.wangcaiToken,
          plate: plate,
          phone: phone,
          insurancecompany: company,
          thirdpartyinsurance: third,
          insurancetype: insurancetype,
          quoteremark: remark,
          state: 1,
          address:address,
          latitude:latitude,
          longitude:longitude,
          formid: that.data.formId
        }:{
          id: that.data.id,
          token: app.globalData.wangcaiToken,
          plate: plate,
          phone: phone,
          insurancecompany: company,
          thirdpartyinsurance: third,
          insurancetype: insurancetype,
          quoteremark: remark,
          state: 1,
          address: address,
          latitude: latitude,
          longitude: longitude,
          formid:that.data.formId
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.data.status == 1) {
            typeof cb == "function" && cb(res.data)
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  //刷新上一页数据
                  var pages = getCurrentPages();
                  if (pages.length > 1) {
                    //上一个页面实例对象
                    var prePage = pages[pages.length - 2];
                    prePage.getData()
                  }
                  wx.navigateBack({
                    delta: 1
                  })
                } 
              }
            })
            returnRes = {
              "status": -1,
              "msg": res.data.msg
            }
            typeof cb == "function" && cb(returnRes)
            return
          }
        }
      })
  },
  deleteRecord: function (cb) {
    var that = this
    wx.showActionSheet({
      itemList: ['删除'],
      itemColor: '#E64340',
      success: function (resSheet) {
        wx.request({
          url: common.postUrl() + 'deleteAutoInsurance',
          data: {
            token: app.globalData.wangcaiToken,
            id: that.data.id
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            if (res.data.status == 1) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                success: function (e) {
                  // 刷新数据
                  typeof cb == "function" && cb(res.data)
                }
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'success'
              })
            }
          }
        })
      }
    })
  },
  detailData: function (e) {
    //请求该id的详细数据
    var that = this
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    })
    wx.request({
      url: common.postUrl() + 'autoInsuranceDetail',
      data: {
        token: app.globalData.wangcaiToken,
        id: that.data.id
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.status == 1) {
          var third = 4
          for(var i=0;i<that.data.thirdArray.length;i++){
            if ((res.data.data.thirdpartyinsurance+'万') == that.data.thirdArray[i]){
              third = i
              break
            }
          }
          that.setData({
            plate: res.data.data.plate,
            phone: res.data.data.phone,
            companyIndex: res.data.data.insurancecompany,
            thirdIndex: third,
            chesun: res.data.data.insurancetype.indexOf('0') >=0?true:false,
            huahen: res.data.data.insurancetype.indexOf('1') >= 0 ? true : false,
            daoqiang: res.data.data.insurancetype.indexOf('2') >= 0 ? true : false,
            ziran: res.data.data.insurancetype.indexOf('3') >= 0 ? true : false,
            boli: res.data.data.insurancetype.indexOf('4') >= 0 ? true : false,
            zuowei: res.data.data.insurancetype.indexOf('5') >= 0 ? true : false,
            bujimianpei: res.data.data.insurancetype.indexOf('6') >= 0 ? true : false,
            guohu: res.data.data.insurancetype.indexOf('7') >= 0 ? true : false,
            fdjtbssx: res.data.data.insurancetype.indexOf('8') >= 0 ? true : false,
            remark: res.data.data.quoteremark,
            address: res.data.data.address == undefined || res.data.data.address == "" || res.data.data.address == null ? '' : res.data.data.address,
            latitude: res.data.data.latitude,
            longitude: res.data.data.longitude
          })
        }else{
          wx.showModal({
            title: '提示',
            content: res.data.data.msg
          })
        }
        wx.hideToast()
      }
    })
  }
})